﻿using System;
using System.Collections.Generic;
using GameFramework.Battle.Core;
using Gameplay.PVE.Utils;
using RootMotion.FinalIK;
using UnityEngine;

namespace Gameplay.PVE.Survivor
{
    public class ParabolaMovement : BulletMovement
    {
        private float moveTime;
        private Vector3 startPosition;
        private Vector3 targetPosition;
        private float startTime;

        private Vector3 velocity;
        private Vector3 velocityHorizontal;
        private float velocityHorizontalValue;
        private Vector3 velocityVertical;
        
        private const float gravity = 9.8f;
        private Vector3 position;
        
        public override void Start()
        {
            isFinish = false;
            startPosition = bullet.Position;
            targetPosition = bullet.targetPosition;
            var startDirection = targetPosition - startPosition;
            startDirection.y = 0;
            startDirection = startDirection.normalized;
            var vv = startDirection.y;
            var startDirectionHorizontal = new Vector3(startDirection.x, 0, startDirection.z);
            var vh = Mathf.Sqrt(startDirection.x * startDirection.x + startDirection.z * startDirection.z);
            var g = gravity;
            var h = startPosition.y;
            var boomHeight = 0f;
            var d = Vector3.Distance(new Vector3(startPosition.x,boomHeight,startPosition.z), targetPosition);
            var result = 2f * vh * vv * d * g + 2f * g * (h - boomHeight) * vh * vh;
            var speedValue = 10f;
            if (result > 0)
            {
                speedValue = d * g / Mathf.Sqrt(result);
            }
            velocity = startDirection.normalized * speedValue;
            velocityHorizontal = startDirectionHorizontal.normalized * speedValue;
            velocityHorizontalValue = speedValue;
            position = startPosition;
        }
        
        public override void Update()
        {
            velocity -= new Vector3(0, gravity, 0) * Time.deltaTime;
            position = position + velocity * Time.deltaTime;
            if (velocity.y < 0 && position.y <= targetPosition.y)
            {
                position.y = targetPosition.y;
                isFinish = true;
                bullet.HitByCollision();
            }
            bullet.Position = position;
        }

        public override bool IsEnd()
        {
            return isFinish;
        }
    }
}
